import concurrent.futures
import multiprocessing
import os

def analyzeRelation(fileList, searchItems):
    relations = {}
    with concurrent.futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()/4*3) as executor:
        def task(file):
            fileRef = {}
            lineNo = 1
            try:
                with open(file, "r", encoding="UTF-8") as f:
                    line = f.readline().strip("\n")
                    while line:
                        for item in searchItems:
                            if item in line:
                                fileRef[item] = fileRef[item] if item in fileRef else []
                                fileRef[item].append({"line": lineNo})
                        line = f.readline().strip("\n")
                        lineNo += 1
            except Exception as e:
                print(f"*****解析{file}出错：", e, "跳过该文件*****\n")
            return file, fileRef
        results = executor.map(task, fileList)
        for fileName, refMap in results:
            for item, refs in refMap.items():
                if item not in relations:
                    relations[item] = {}
                relations[item][fileName] = refs
    return relations

def printRelations(relations):
    for fileName, refMap in relations.items():
        print(f"{fileName}：")
        for refName, refs in refMap.items():
            print(f"\t{refName}：")
            for ref in refs:
                print(f"\t\t{ref}")

def analyze(path, deep=False):
    path = path.strip("\\")
    loopFiles = [] # 需要遍历的文件内容
    if not deep:
        for name in os.listdir(path):
            absPath = f"{path}\\{name}"
            if os.path.isfile(absPath):
                loopFiles.append(absPath)
    else:
        for root, _dir, files in os.walk(path):
            for file in files:
                absPath = f"{root}\\{file}"
                loopFiles.append(absPath)
    return analyzeRelation(loopFiles, [os.path.basename(item) for item in loopFiles])

if __name__ == '__main__':
    pass
